import axios from 'axios'
import { ElMessage } from 'element-plus'

// 是否使用本地模拟数据（当后端API不可用时）
const useMockData = false

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 15000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    
    // 添加详细日志
    if (config.url.includes('/search')) {
      console.log('搜索请求:', {
        url: config.url,
        method: config.method,
        params: config.params,
        data: config.data
      })
    }
    
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 添加详细日志
    if (response.config.url.includes('/search')) {
      console.log('搜索响应:', res)
    }
    
    // 如果返回的状态码不是200，说明接口出错了
    if (res.code !== 200) {
      // 搜索相关API错误不需要显示全局提示，由组件内部处理
      if (!response.config.url.includes('/search')) {
        ElMessage.error(res.message || '系统错误')
      }
      
      // 401: 未登录或token过期
      if (res.code === 401) {
        // 清除token
        localStorage.removeItem('token')
        
        // 避免在登录页面重复跳转
        if (!window.location.pathname.includes('/login')) {
          // 使用路由跳转而不是直接修改location
          setTimeout(() => {
            window.location.href = '/login'
          }, 1000)
        }
      }
      
      return Promise.reject(new Error(res.message || '系统错误'))
    } else {
      return res
    }
  },
  error => {
    console.error('响应错误:', error)
    
    // 获取请求配置
    const config = error.config || {}
    
    // 自定义错误信息
    let errorMessage = '网络连接失败，请检查您的网络'
    
    // 根据状态码定制错误信息
    if (error.response) {
      const { status } = error.response
      
      switch (status) {
        case 400:
          errorMessage = '请求参数错误'
          break
        case 401:
          errorMessage = '未登录或登录已过期'
          // 清除token
          localStorage.removeItem('token')
          // 避免在登录页面重复跳转
          if (!window.location.pathname.includes('/login')) {
            setTimeout(() => {
              window.location.href = '/login'
            }, 1000)
          }
          break
        case 403:
          errorMessage = '您没有权限访问该资源'
          break
        case 404:
          errorMessage = '请求的资源不存在'
          break
        case 429:
          errorMessage = '请求过于频繁，请稍后再试'
          break
        case 500:
          errorMessage = '服务器内部错误'
          break
        case 502:
          errorMessage = '网关错误'
          break
        case 503:
          errorMessage = '服务不可用'
          break
        case 504:
          errorMessage = '网关超时'
          break
        default:
          errorMessage = `请求失败(${status})`
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应
      errorMessage = '服务器未响应，请稍后再试'
    } else if (error.message) {
      if (error.message.includes('timeout')) {
        errorMessage = '请求超时，请稍后再试'
      }
    }
    
    // 搜索相关API错误不需要显示全局提示，由组件内部处理
    if (!config.url || !config.url.includes('/search')) {
      ElMessage.error(errorMessage)
    }
    
    // 如果使用模拟数据且是特定错误（如网络错误或404），返回模拟数据
    if (useMockData && (error.message.includes('Network Error') || error.response?.status === 404)) {
      console.warn('使用模拟数据替代API响应')
      
      // 解析请求URL和方法，为不同API提供不同的模拟数据
      const { url, method } = error.config
      
      // 构造模拟响应
      if (url.includes('/questions')) {
        if (method === 'get') {
          if (url.includes('/hot')) {
            return mockSuccessResponse([])
          } else if (url.includes('/answers')) {
            return mockSuccessResponse({ records: [], total: 0, current: 1, size: 10 })
          } else {
            const idMatch = url.match(/\/questions\/(\d+)/)
            if (idMatch) {
              return mockSuccessResponse({
                id: parseInt(idMatch[1]),
                title: '模拟问题标题',
                content: '这是一个模拟问题的内容',
                userId: 1,
                nickname: '模拟用户',
                createTime: new Date().toISOString(),
                viewCount: 100,
                answerCount: 5,
                status: 1
              })
            } else {
              return mockSuccessResponse({ 
                records: [
                  {
                    id: 1,
                    title: '模拟问题1',
                    content: '模拟问题内容',
                    createTime: new Date().toISOString(),
                    userId: 1,
                    nickname: '用户1',
                    viewCount: 100,
                    answerCount: 5
                  }
                ], 
                total: 1, 
                current: 1, 
                size: 10 
              })
            }
          }
        }
      } else if (url.includes('/collections') || url.includes('/votes') || url.includes('/shares')) {
        return mockSuccessResponse(method === 'get' ? true : {})
      } else if (url.includes('/comments')) {
        return mockSuccessResponse({ records: [], total: 0 })
      } else if (url.includes('/users/notifications/settings')) {
        // 模拟通知设置数据
        if (method === 'get') {
          return mockSuccessResponse({
            questionReply: true,
            answerComment: true,
            answerAccepted: true,
            receiveLike: true,
            emailNotify: false,
            weeklyEmail: false
          })
        } else {
          return mockSuccessResponse({ success: true })
        }
      } else if (url.includes('/users/privacy/settings')) {
        // 模拟隐私设置数据
        if (method === 'get') {
          return mockSuccessResponse({
            profileVisibility: 'public',
            questionsVisibility: 'public',
            showFollowing: true,
            showFollowers: true
          })
        } else {
          return mockSuccessResponse({ success: true })
        }
      } else if (url.includes('/users/password')) {
        // 模拟密码修改响应
        return mockSuccessResponse({ success: true })
      } else if (url.includes('/users/email')) {
        // 模拟邮箱绑定响应
        return mockSuccessResponse({ success: true })
      } else if (url.includes('/upload/avatar')) {
        // 模拟头像上传响应
        return mockSuccessResponse('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
      } else if (url.includes('/users/me')) {
        // 模拟当前用户信息
        return mockSuccessResponse({
          id: 1,
          username: '测试用户',
          nickname: '昵称',
          email: 'test@example.com',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          bio: '这是个人简介',
          gender: 1,
          profession: '软件工程师',
          location: '北京,朝阳区',
          createTime: '2023-01-01T00:00:00Z',
          role: 1,
          followerCount: 10,
          followingCount: 5
        })
      } else if (url.includes('/search/questions')) {
        // 模拟搜索问题结果
        const params = new URLSearchParams(url.split('?')[1]);
        const keyword = params.get('keyword') || '';
        const searchType = params.get('type') || 'all';
        
        return mockSuccessResponse({
          records: [
            {
              id: 1,
              title: `搜索结果: ${keyword} 问题1`,
              content: `这是包含关键词 "${keyword}" 的问题内容，仅用于模拟搜索结果...`,
              created_at: new Date().toISOString(),
              updated_at: new Date().toISOString(),
              user_id: 1,
              user: {
                id: 1,
                username: '测试用户',
                avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
              },
              views_count: 123,
              answers_count: 5,
              votes_count: 10,
              tags: 'javascript,vue,前端',
              is_bookmarked: false,
              is_liked: false
            },
            {
              id: 2,
              title: `搜索结果: ${keyword} 问题2`,
              content: `另一个包含 "${keyword}" 的问题内容示例...`,
              created_at: new Date(Date.now() - 86400000).toISOString(), // 1天前
              updated_at: new Date(Date.now() - 86400000).toISOString(),
              user_id: 2,
              user: {
                id: 2,
                username: '另一用户',
                avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
              },
              views_count: 89,
              answers_count: 3,
              votes_count: 7,
              tags: 'java,spring,后端',
              is_bookmarked: true,
              is_liked: false
            }
          ],
          total: 2,
          current: 1,
          size: 10
        });
      } else if (url.includes('/search/users')) {
        // 模拟搜索用户结果
        return mockSuccessResponse({
          records: [
            {
              id: 1,
              username: '测试用户',
              nickname: '昵称',
              avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
              bio: '用户简介信息...',
              followerCount: 10,
              isFollowing: false
            },
            {
              id: 2,
              username: '另一用户',
              nickname: '小明',
              avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
              bio: '另一个用户的简介...',
              followerCount: 5,
              isFollowing: true
            }
          ],
          total: 2,
          current: 1,
          size: 10
        });
      } else if (url.includes('/search/hot-keywords')) {
        // 模拟热门搜索关键词
        return mockSuccessResponse([
          '前端开发',
          'Vue.js',
          'Java',
          'Python',
          'Spring Boot',
          '算法',
          '面试题',
          '微服务'
        ]);
      } else if (url.includes('/search/history')) {
        if (method === 'get') {
          // 模拟获取搜索历史
          return mockSuccessResponse([
            '前端开发',
            'Vue.js',
            'JavaScript',
            '性能优化'
          ]);
        } else if (method === 'post') {
          // 模拟保存搜索历史
          return mockSuccessResponse({ success: true });
        } else if (method === 'delete') {
          // 模拟清除搜索历史
          return mockSuccessResponse({ success: true });
        }
      }
      
      // 默认返回空成功响应
      return mockSuccessResponse({})
    }
    
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

// 构造模拟成功响应
function mockSuccessResponse(data) {
  return {
    code: 200,
    data,
    message: 'success'
  }
}

export default service 